import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { loginApi, logoutApi, getCurrentUserApi } from '@/api/login'
import tokenManager from '@/utils/tokenManager'
import { handleApiError, handleSuccess } from '@/utils/errorUtils'

export const useLoginStore = defineStore('login', () => {
  // 状态定义
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))
  const isLoading = ref(false)
  const router = useRouter()

  // 检查是否已登录
  const isLoggedIn = () => {
    return !!tokenManager.getToken() && !!userInfo.value
  }

  // 获取token信息
  const getTokenInfo = () => {
    return tokenManager.getTokenInfo()
  }

  // 用户登录
  const login = async (username, password) => {
    try {
      isLoading.value = true
      const response = await loginApi({ username, password })
      
      userInfo.value = response.data?.user_info || response.user_info || response.user || null
      if (userInfo.value) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
      }
      
      if (response.data?.token) {
        tokenManager.onLoginSuccess(response.data.token)
      } else {
        console.error('登录响应中缺少token，响应数据：', response)
      }
      return true
    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 用户登出
  const logout = async () => {
    try {
      isLoading.value = true
      await logoutApi()
      
      tokenManager.onLogout()
      userInfo.value = null
      return true
    } catch (error) {
      tokenManager.onLogout()
      userInfo.value = null
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 获取当前用户信息
  const getCurrentUser = async () => {
    try {
      isLoading.value = true
      const response = await getCurrentUserApi()
      userInfo.value = response.data?.user_info || response.user_info || response
      if (userInfo.value) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
      }
      return userInfo.value
    } catch (error) {
      return null
    } finally {
      isLoading.value = false
    }
  }

  // 处理用户登录
  const handleLogin = async (username, password) => {
    try {
      const success = await login(username, password)
      if (success) {
        handleSuccess('登录成功')
        router.push('/home')
      }
      return success
    } catch (error) {
      handleApiError(error, '登录失败')
      return false
    }
  }

  return {
    // 状态
    userInfo,
    isLoading,
    
    // 工具方法
    isLoggedIn,
    getTokenInfo,
    
    // API方法
    login,
    logout,
    getCurrentUser,
    
    // 业务方法
    handleLogin
  }
})